#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<dirent.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include"../include/client.h"

/* 功能：从设备文件中截取温度字符串
 * 参数：temp:传出截取温度字符串地址
 *       chip:传出设备芯片号
 * 返回值：成功返回0，失败返回-1
 * */
int DS_get_tem(float *temp,char *chip)
{
        DIR                *dp;//保存目录信息结构体
        struct dirent      *dirp;//保存文件信息结构体
        char               w1_path[30] = "/sys/bus/w1/devices/";//设备所在的目录
        int                found = 0;
        int                fd;//文件描述符
        char               *ptr;
        char               buf[100];//存文件的内容,文件内容比较少，直接使用buf
        
        //打开一个目录
        if((dp = opendir(w1_path)) < 0)
        {
                printf("opendir w1_path failed: %s\n",strerror(errno));
                mylog(__func__,__LINE__,ERROR,"opendir w1_path failed:%s",strerror(errno));

        }
        
        //扫描该目录下的文件
        while((dirp = readdir(dp)) != NULL)
        {
                if(strstr(dirp->d_name,"28-") > 0)//寻找28开头的目录
                {
                        strcpy(chip,dirp->d_name);//将目录拷贝到chip里面，这里的目录名就是设备号
                        found = 1;//表示已经找到设备号了
                        break;
                }
        }
        closedir(dp);//关闭目录
        strncat(w1_path,chip,sizeof(w1_path));//将设备目录追加到文件路径下
        strncat(w1_path,"/w1_slave",sizeof(w1_path));//再将设备目录下保存温度的文件名追加到路径下
   
        if(!found)//表示没有发现设备目录
        {
                printf("readdir failed and can't find device dir!\n");
                mylog(__func__,__LINE__,ERROR,"readdir failed and can't find device dir!");
        } 
        
        
        if((fd=open(w1_path,O_RDONLY)) < 0)//打开文件
        {
                printf("open w1_path failed: %s\n",strerror(errno));
                mylog(__func__,__LINE__,ERROR,"open w1_path failed:%s",strerror(errno));
                close(fd);
        }


        if(read(fd,buf,sizeof(buf)) < 0)//将文件内容读到buf缓冲区里面
        {
                printf("read from w1_path failed: %s\n",strerror(errno));
                mylog(__func__,__LINE__,ERROR,"read from w1_path failed:%s",strerror(errno));
                close(fd);
        }
       
        ptr = strstr(buf,"t=");//截取温度部分
        if(!ptr)
        {
            printf("ERROR:can't get temperature\n");
            mylog(__func__,__LINE__,ERROR,"ERROR:can't get temperature!");
        }

        mylog(__func__,__LINE__,INFO,"Getting tempreature successgully!");

        ptr+=2;//去掉"t="
        *temp = atof(ptr)/1000;//将字符串转化为double型

        return 0;
}


